package com.danbay.framework.kafka.coap;

import com.danbay.framework.utils.StringUtils;
import com.xiaoleilu.hutool.util.NetUtil;
import org.apache.commons.lang3.RandomUtils;
import org.joda.time.DateTime;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 消息序号
 *
 * @author SJG
 *         2017/11/13.
 */
public class CoAPToken {

    private static String lastIpPart = "1";
    private static int rndInt= RandomUtils.nextInt(1,99);
    private static int maxSequence=900;

    static {
        //取得本机ip最后一段
        String ip = NetUtil.getLocalhost().getHostAddress();
        lastIpPart = ip.substring(ip.lastIndexOf(".") + 1);
    }

    private static AtomicLong sequenceAto = new AtomicLong(0);

    /**
     * 取下一个序号
     * 1~8位
     * @return 序号
     */
    public static Long getNextToken() {
        //以ip最后一段+2位随机数 为前缀
        String prefix=lastIpPart+rndInt;
        int idLen=8;
        String id = StringUtils.rightPad(prefix, idLen, '0');
        Long increaseId=sequenceAto.incrementAndGet();
        Long token = Long.parseLong(id) + increaseId;
        //例id:10101900
        //如果token大于900从1开始
        if(increaseId>=maxSequence){
            sequenceAto.compareAndSet(increaseId,0);
        }
        return token;
    }
}
